﻿using CaroLibraly;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using System.Runtime.Serialization.Formatters;
using System.Text;
using System.Threading.Tasks;
using ThuVienWinform.Mang;

namespace CaroClient
{
    public class Global
    {
        private static HttpChannel channel;

        public static IServer Server { set; get; }
        public static bool Connected { set; get; }
        public static Player Player { set; get; }


        static Global()
        {
            Global.Connected = false;
            Global.Player = new Player(Mang.TenMay, Mang.DanhSachIpCaNhan[0]);
        }

        public static void Connect(string _ipserver)
        {
            try
            {
                SoapServerFormatterSinkProvider serverProvider = new SoapServerFormatterSinkProvider();
                SoapClientFormatterSinkProvider clientProvider = new SoapClientFormatterSinkProvider();

                serverProvider.TypeFilterLevel = TypeFilterLevel.Full;

                IDictionary props = new Hashtable();
                props["port"] = 0;
                string s = System.Guid.NewGuid().ToString();
                props["name"] = s;
                props["typeFilterLevel"] = TypeFilterLevel.Full;

                channel = new HttpChannel(props, clientProvider, serverProvider);

                ChannelServices.RegisterChannel(channel);

                //WellKnownClientTypeEntry w = new WellKnownClientTypeEntry("ThuVienWinformCHAT.IThuVienWinformChat", "ThuVienWinformCHAT", "ThuVienWinformCHAT");
                WellKnownServiceTypeEntry w = new WellKnownServiceTypeEntry(InfoServer.NameClass
                    , InfoServer.NameSpace
                    , InfoServer.ServerName
                    , WellKnownObjectMode.Singleton
                    );

                Global.Server = (IServer)Activator.GetObject(typeof(IServer), "http://" + _ipserver + ":" + InfoServer.Port + "/"+InfoServer.ServerName, w);

                Global.Connected = Global.Server.Connected;
            }
            catch
            {
                Global.Connected = false;
            }
        }
    }
}
